'use client';

import React from 'react';
import { TaskModel } from '../lib/api';

const DEFAULT_COLUMNS = ['open', 'in_progress', 'done', 'closed'];

interface Props {
  tasks: TaskModel[] | undefined;
  loading: boolean;
  onMove: (task: TaskModel, nextStatus: string) => void;
}

export function TaskBoard({ tasks, loading, onMove }: Props) {
  const grouped = React.useMemo(() => {
    const map = new Map<string, TaskModel[]>();
    DEFAULT_COLUMNS.forEach(col => map.set(col, []));
    (tasks ?? []).forEach(task => {
      const key = map.has(task.status) ? task.status : 'open';
      map.get(key)?.push(task);
    });
    return map;
  }, [tasks]);

  return (
    <section className="panel">
      <header className="panel-header">
        <div>
          <h2>Tasks</h2>
          <span className="muted">Kanban board derived from timeline events</span>
        </div>
      </header>
      <div className="panel-body board">
        {loading && <p className="muted">Loading tasks…</p>}
        {!loading && DEFAULT_COLUMNS.map(column => (
          <div key={column} className="column">
            <header>{column.replace('_', ' ')}</header>
            <div className="column-body">
              {grouped.get(column)?.map(task => (
                <article key={task.id} className="task-card">
                  <header>
                    <h3>{task.title || '(untitled)'}</h3>
                    <span className="muted">{task.actor}</span>
                  </header>
                  <p>{task.description}</p>
                  <footer>
                    <span className="muted">{new Date(task.created_at).toLocaleString()}</span>
                    <div className="moves">
                      {DEFAULT_COLUMNS.filter(s => s !== task.status).map(status => (
                        <button key={status} className="ghost small" onClick={() => onMove(task, status)}>
                          {status.replace('_', ' ')}
                        </button>
                      ))}
                    </div>
                  </footer>
                </article>
              ))}
              {grouped.get(column)?.length === 0 && <p className="muted">No tasks</p>}
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}
